package com.morningstar.qs.api.basic.common.encrypt.rsa;

import java.security.Key;

import javax.crypto.Cipher;

public class SecUtil {
	private static final String RSA = "RSA";
	public static byte[] encrypt(Key key,byte[] source) throws Exception{
		Cipher cipher = Cipher.getInstance(RSA);
		cipher.init(Cipher.ENCRYPT_MODE, key);
		return cipher.doFinal(source);
	}
	
	public static String encrypt(Key key, String source) throws Exception{
		return byte2hex(encrypt(key,source.getBytes()));
	}
	private static String byte2hex(byte[] b) {  
        String hs = "";  
        String stmp = "";  
        for (int n = 0; n < b.length; n++) {  
            stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));  
            if (stmp.length() == 1){  
                hs = hs + "0" + stmp;  
            }else{  
                hs = hs + stmp;  
            }  
        }  
        return hs.toUpperCase();  
    }  
	private static byte[] hex2byte(byte[] b) {  
        if ((b.length % 2) != 0)  
            throw new IllegalArgumentException("even length");  
        byte[] b2 = new byte[b.length / 2];  
        for (int n = 0; n < b.length; n += 2) {  
            String item = new String(b, n, 2);  
            b2[n / 2] = (byte) Integer.parseInt(item, 16);  
        }  
        return b2;  
    }  
	public static byte[] decrypt(Key key, byte[] source) throws Exception {
		Cipher cipher = Cipher.getInstance(RSA);
		cipher.init(Cipher.DECRYPT_MODE, key);
		return cipher.doFinal(source);
	}
	
	public static String decrypt(Key key, String source) throws Exception{
		return new String(decrypt(key,hex2byte(source.getBytes())));
	}
	
	
}
